//
//  JBSBusDetailViewController.m
//  changwonbus
//
//  Created by JunHyungLee on 12. 11. 24..
//  Copyright (c) 2012년 park juram. All rights reserved.
//

#import "JBSBusDetailViewController.h"
#import "JBSBusDetailTableViewCell.h"
#import "JBSBusStopDetailViewController.h"
#import "HttpRequest.h"
#import "HTMLParser.h"
#import "HTMLNode.h"

@interface JBSBusDetailViewController ()

@end

@implementation JBSBusDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:_busNumber];
    
    [self requestPostURL];
    // Do any additional setup after loading the view.
//    [self setTitle:[[NSString alloc] initWithFormat:@"%@[%@]", _busNumber, _busPath]];
    
}
- (IBAction)requestPostBtn:(id)sender {
    [self requestPostURL];
}
- (void) requestPostURL
{
    nibsRegistered = NO;
	
    if ( _dataArray == nil ) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    [_dataArray removeAllObjects];
    
    //    NSString *url = @"http://bus.changwon.go.kr/busInfo/routeImg.jsp?routeid=";
    NSString *url = [[NSString alloc] initWithFormat:@"http://bus.changwon.go.kr/busInfo/routeImg.jsp?routeid=%@", _busNumberId ];
    
    // HTTP Request 인스턴스 생성
    HttpRequest *httpRequest = [[HttpRequest alloc] init];
    
    //    // POST로 전송할 데이터 설정
    //    NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:
    //                                @"0", @"ra_type",
    //                                [_searchBar text], @"search_title",
    //                                nil];
    //NSString *bodyObject = @"type=getUser&seq=1&latitude=38.0&longitude=127.0&time=13600&unit='k'&distance=9999";
    
    // 통신 완료 후 호출할 델리게이트 셀렉터 설정
    [httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];
    
    // 페이지 호출
    [httpRequest requestUrlGet:url bodyObject:nil];
    
}
-(void)didReceiveFinished:(NSString *)receiveString
{
//    NSLog(@"%@", receiveString );
    HTMLParser *parser = [[HTMLParser alloc] initWithString:receiveString error:nil ];
    HTMLNode *bodyNode = [parser body];
    HTMLNode *contentsNode = [bodyNode findChildOfClass:@"lineType"];
    NSArray *busArray = [contentsNode findChildTags:@"div"];
    NSArray *stopArray = [[contentsNode findChildTag:@"ol"] findChildTags:@"li"];
    
    NSMutableDictionary *busInfoDic = [[NSMutableDictionary alloc] init];
    
    for ( int i=0; i<[busArray count]; i++ ) {
        HTMLNode *bus = [[busArray objectAtIndex:i] findChildTag:@"b"];
        NSString *positionNumber = [bus getAttributeNamed:@"id"];
        positionNumber = [positionNumber substringFromIndex:7];
        NSString *busNumber = [bus contents];
        
        [busInfoDic setValue:busNumber forKey:positionNumber];
//        NSLog(@"%@ : %@", positionNumber, busNumber );
    }
    
    for ( int i=0; i<[stopArray count]; i++ ) {
        HTMLNode *stop = [stopArray objectAtIndex:i];
        NSString *sStop = [stop getAttributeNamed:@"id"];
        sStop = [sStop substringFromIndex:3];
        
        NSArray *spanArray = [stop findChildTags:@"span"];
        HTMLNode *lineNode = [spanArray objectAtIndex:0];
        HTMLNode *titleNode = [spanArray objectAtIndex:1];
        HTMLNode *idNode = [spanArray objectAtIndex:2];
        
        HTMLNode *trafficNode;
        if ( [spanArray count] >=7 )
            trafficNode = [spanArray objectAtIndex:6];
        else trafficNode = nil;

        
        NSString *sLine = [lineNode className];
        NSString *sTitle = [titleNode getAttributeNamed:@"title"];
        NSString *sId = [idNode getAttributeNamed:@"title"];
        NSString *sTraffic = [trafficNode className];
        
        if ( i < 50 ) {
            if ( [busInfoDic valueForKey:sStop] != nil ) {
                NSLog(@"%@---%@ : %@ : %@ : %@ : %@ ", [busInfoDic valueForKey:sStop], sStop, sLine, sTitle, sId, sTraffic );
            } else {
                NSLog(@"%@ : %@ : %@ : %@ : %@ ", sStop, sLine, sTitle, sId, sTraffic );
            }
        }
        NSDictionary *data;
        if ( [busInfoDic valueForKey:sStop] != nil ) {
            data = [[NSDictionary alloc] initWithObjectsAndKeys: [busInfoDic valueForKey:sStop],@"busnumber", sStop,@"stop",sLine,@"line",sTitle,@"title",sId,@"id",sTraffic,@"traffic", nil];
        } else {
            data = [[NSDictionary alloc] initWithObjectsAndKeys: sStop,@"stop",sLine,@"line",sTitle,@"title",sId,@"id",sTraffic,@"traffic", nil];
        }
        
        [_dataArray addObject:data];
        
    }
    
    [_busDetailTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"BusDetailTableCell";
//    nibsRegistered = NO;
    if ( !nibsRegistered ) {
        UINib *nib = [UINib nibWithNibName:@"BusDetailTableCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
        nibsRegistered = YES;
    }
    
    JBSBusDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    NSInteger row = [indexPath row];
    NSDictionary *rowData = [_dataArray objectAtIndex:row];
    
    [cell.stopBusNumber setText:[rowData objectForKey:@"busnumber"]];
    if([rowData objectForKey:@"busnumber"] != nil)
    {
        cell.stopIsBus.image = [UIImage imageNamed:@"buschangwon.png"];
    }
    [cell.stopDirection setText:[rowData objectForKey:@"line"]];
    [cell.stopName setText:[rowData objectForKey:@"title"]];
    [cell.stopNumber setText:[rowData objectForKey:@"id"]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger row = [indexPath row];
    NSDictionary *rowData = [_dataArray objectAtIndex:row];
    
    if([[rowData objectForKey:@"id"] isEqualToString:@"0"])
    {
        
        return;
    }
    // HTTP Request 인스턴스 생성
    HttpRequest *httpRequest = [[HttpRequest alloc] init];
    NSString *url = [[NSString alloc] initWithFormat:@"http://bus.changwon.go.kr/busInfo/busInfoDetail.jsp?ra_type=1&search_title=%@",[rowData objectForKey:@"id"]];
    //NSString *url = @"http://bus.changwon.go.kr/busInfo/busInfoDetail.jsp?ra_type=1&search_title=1";
    
    // POST로 전송할 데이터 설정
 //   NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:								@"1", @"ra_type",								[rowData objectForKey:@"id"], @"search_title",							nil];
    
       // 통신 완료 후 호출할 델리게이트 셀렉터 설정
    [httpRequest setDelegate:self selector:@selector(didFinishSearchBusStopId:)];
    
    // 페이지 호출
    [httpRequest requestUrlGet:url bodyObject:nil];
}
-(void) didFinishSearchBusStopId:(NSString *)receiveString
{
    HTMLParser *parser = [[HTMLParser alloc]
                          initWithString:receiveString error:nil];
    
    NSLog( @"%@", receiveString );
    
    HTMLNode *bodyNode = [parser body];
    NSArray *searchResult = [[[bodyNode findChildOfClass:@"search_result2"] findChildOfClass:@"scroll"] findChildTags:@"tr"];
    
    HTMLNode *busStopNumberNode = [[searchResult objectAtIndex:0] findChildTag:@"strong"];
    HTMLNode *busStopNameNode = [[searchResult objectAtIndex:0] findChildWithAttribute:@"width" matchingName:@"120" allowPartial:YES];
        
    NSString *busStopNumber = [busStopNumberNode contents];
    NSString *busStopName = [busStopNameNode contents];
    NSString *busStopId = [[[searchResult objectAtIndex:0] findChildTag:@"a"] getAttributeNamed:@"onclick"];
        
    NSRange startPos = [busStopId rangeOfString:@"'"];
    NSRange endPos = [busStopId rangeOfString:@"'" options:NSBackwardsSearch];
    startPos.location += 1;
        
    startPos.length = endPos.location - startPos.location;
    busStopId = [busStopId substringWithRange:startPos];
    _segueData = [[NSDictionary alloc]initWithObjectsAndKeys:busStopNumber, @"busStopNumber", busStopName, @"busStopName", busStopId, @"busStopId", nil];
    
    NSLog(@"%@---%@", [_segueData objectForKey:@"busStopId"], busStopId);

    [self performSegueWithIdentifier: @"BusToBusStopDetail" sender: self];

}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"BusToBusStopDetail"]) {
        
        JBSBusStopDetailViewController *destViewController = segue.destinationViewController;
        destViewController.busStopId = [_segueData objectForKey:@"busStopId"];
        destViewController.busStopName = [_segueData objectForKey:@"busStopName"];
        destViewController.busStopNumber = [_segueData objectForKey:@"busStopNumber"];        
               
    }
}

@end
